package com.itcam.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itcam.tingshu.album.service.AlbumInfoService;
import com.itcam.tingshu.common.constant.KafkaConstant;
import com.itcam.tingshu.vo.album.TrackStatMqVo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AlbumReceiver {


    @Autowired
    private AlbumInfoService albumInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 更新声音，专辑播放量
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String, String> record) {
        // 获取发送的消息
        String strJson = record.value();
        if (!StringUtils.isEmpty(strJson)) {
            // 将这个json字符串转换为对象
            TrackStatMqVo trackStatMqVo = JSON.parseObject(strJson, TrackStatMqVo.class);
            //  业务编号：去重使用
            String businessNo = trackStatMqVo.getBusinessNo();
            // 第一次执行，则result=true
            Boolean result = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 1, TimeUnit.DAYS);
            // 更新播放量
            try {
                albumInfoService.trackStatUpdate(trackStatMqVo);
            } catch (Exception e) {
                //  如果有异常，则删除原有的key.
                redisTemplate.delete(businessNo);
                throw new RuntimeException(e);
            }
        }
    }
}